package com.baoyouqun.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baoyouqun.domain.VO.KeywordFrequencyVO;
import com.baoyouqun.entity.UserSearchRecord;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;


@Mapper
public interface UserSearchRecordMapper extends BaseMapper<UserSearchRecord> {

    /**
     * 新增方法：支持分页、关键词模糊查询、频次排序的高频词查询
     *
     * @param page    分页对象（MyBatis-Plus分页插件自动处理limit和offset）
     * @param keyword 模糊查询关键词（可为null）
     * @param isAsc   排序方式（true=升序，false=降序）
     * @return 分页后的关键词频次列表
     */
    @Select("<script>" +
            "SELECT " +
            "  search_keyword AS keyword,  " +
            "  COUNT(*) AS frequency       " +
            "FROM " +
            "  user_search_record          " +
            // 模糊查询条件（关键词不为null时才拼接）
            "<where>" +
            "  <if test='keyword != null and keyword != \"\"'>" +
            "    search_keyword LIKE CONCAT('%', #{keyword}, '%') " +
            "  </if>" +
            "</where>" +
            "GROUP BY " +
            "  search_keyword              " +
            // 排序条件（根据isAsc动态切换升序/降序）
            "ORDER BY " +
            "  frequency <if test='isAsc'>ASC</if><if test='!isAsc'>DESC</if> " +
            "</script>")
    Page<KeywordFrequencyVO> selectKeywordFrequencyByPage(
            Page<KeywordFrequencyVO> page,
            @Param("keyword") String keyword,
            @Param("isAsc") boolean isAsc);
}